// import { login} from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'
import { login, getUserInfo, getUserDetailById } from '@/api/user'

const state = {
  token: getToken() || '',
  userInfo: {}
}

const mutations = {
  setToken(state, payload) {
    state.token = payload
    setToken(payload)
  },
  setUserInfo(state, payload) {
    state.userInfo = payload
  },
  // 删除缓存
  removeInfo(state) {
    state.token = ''
    state.userInfo = {}
    removeToken()
  }
}

const actions = {
  // 存储token
  asyncSetToken(ctx, payload) {
    return new Promise((resolve, reject) => {
      login(payload).then(res => {
        ctx.commit('setToken', res)
        resolve()
      })
    })
  },
  // 存储用户信息
  asyncSetUserInfo(ctx) {
    return new Promise((resolve, reject) => {
      getUserInfo().then(res => {
        getUserDetailById(res.userId).then(imgRes => {
          ctx.commit('setUserInfo', { ...res, ...imgRes })
          resolve()
        })
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

